//
//  FirstViewController.m
//  iTrack
//
//  Created by Sergei Sevriugin on 6/11/10.
//  Copyright 2010 Bellwood Systems. All rights reserved.
//

#import "FirstViewController.h"
#import "LoginViewController.h"


@implementation FirstViewController

@synthesize gmaps;
@synthesize updated;

#pragma mark -
#pragma mark View Data management

- (void) waitForData {
	
	UIViewController *indicatorViewController = [[UIViewController alloc] initWithNibName:@"IndicatorView" bundle:nil];
	
	[self presentModalViewController:indicatorViewController animated:YES];
	
	[indicatorViewController release];
}


- (void) stopWaitForData {
	
	[[self tableView] reloadData];

	[self dismissModalViewControllerAnimated:YES];
	
	if (mapAdded) {
		mapAdded = NO;
	}
}

- (void) loadData {
	[[self tableView] reloadData];
}

#pragma mark -
#pragma mark Initialization



/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if ((self = [super initWithStyle:style])) {
	
		navigation = [[UINavigationController alloc] initWithRootViewController:self];
		
		}		
    return self;
}
*/

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	
	showMap		= NO;
	showWeb		= NO;
	mapAdded	= NO;
	
	updated		= NO;
 
	if (gmaps) {
		[gmaps setActiveView:self];
		[gmaps fetchMaps];		
	}
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

	if (self.updated) {
		[[self tableView] reloadData];
	}	
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

	if ([gmaps getError]) {
		[self loginClicked:self];
	}
	
}

/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
	return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    
	return [gmaps countOfMaps];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
	GDataEntryMap* map		= [gmaps getMapAtIndex:indexPath.row];
	
    // Configure the cell...
	
	NSString* mapTitle;
	NSString* mapSummary;
	
	mapTitle	= [[map title] stringValue];
	mapSummary	= [[map summary] stringValue];
	
    [[cell textLabel] setText:mapTitle];
	[[cell detailTextLabel] setText:mapSummary];
	
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
		
		[gmaps setActiveView:self];		
		[gmaps deleteMap:indexPath.row];
        //[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}



/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark -
#pragma mark Table view delegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	if (showMap == YES) {
		if (showWeb) {
			UIViewController*	webViewController		= [[UIViewController alloc] initWithNibName:@"WebView" bundle:nil];
			UIWebView*			webVew					= (UIWebView*) [webViewController view];
			GDataEntryMap*		map						= [gmaps getMapAtIndex:indexPath.row];
			NSURL*				mapHTMLLink				= [[map HTMLLink] URL];
			NSURLRequest*		request					= [NSURLRequest requestWithURL:mapHTMLLink];
			
			[webVew loadRequest:request];
			
			[self.navigationController pushViewController:webViewController animated:YES];
			[webViewController release];
		}
		else {
			MapViewController*	detailViewController	= [[MapViewController alloc] initWithNibName:@"GoogleMapView" bundle:nil];
			MKMapView*			mapView					= (MKMapView *) [detailViewController view];
			// Setup controller properties
			[detailViewController setGmaps:gmaps];
			[detailViewController setCurrentMapId:indexPath.row];
			[mapView setDelegate:detailViewController];
			
			UIBarButtonItem *recItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"play32.png"]
																		style:UIBarButtonItemStylePlain
																		target:detailViewController
																		action:@selector(recClicked:)];
			recItem.width		= 92.0;
			
			UIBarButtonItem *pauseItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"pause32.png"]
																		style:UIBarButtonItemStylePlain
																		target:detailViewController
																		action:@selector(pauseClicked:)];
			pauseItem.width		= 92.0;
			pauseItem.enabled	= NO;
			
			UIBarButtonItem *addItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"plus32.png"]
																		style:UIBarButtonItemStylePlain
																		target:detailViewController
																		action:@selector(addClicked:)];
			addItem.width		= 92.0;
			addItem.enabled		= NO;
			
			NSArray *items = [NSArray arrayWithObjects: recItem, pauseItem, addItem, nil];
			
			[detailViewController setToolbarItems:items animated:NO];
			
			[self.navigationController pushViewController:detailViewController animated:YES];
			[detailViewController release];
		}	
	}
	else {
		FeaturesViewController *detailViewController = [[FeaturesViewController alloc] initWithNibName:@"FeaturesView" bundle:nil];
		// Setup controller properties
		[detailViewController setGmaps:gmaps];
		[detailViewController setCurrentMapId:indexPath.row];
		[detailViewController setRoot_controller:self];
		[detailViewController setUpdated:NO];
						
		// Pass the selected object to the new view controller.
		
		[self.navigationController pushViewController:detailViewController animated:YES];
		[detailViewController release];
	}
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}

#pragma mark -
#pragma mark ToolBar Event management

-(IBAction)tabClicked:(id)sender {	
	showMap = NO;
	showWeb	= NO;
	
	[[[self.navigationController navigationBar] topItem] setTitle:@"TABLE: My Maps"];
	
	NSArray*			items	= [self toolbarItems];
	
	UIBarButtonItem*	tabItem	= [items objectAtIndex:1];
	UIBarButtonItem*	webItem	= [items objectAtIndex:3];
	UIBarButtonItem*	mapItem	= [items objectAtIndex:2];
	
	tabItem.enabled				= NO;
	webItem.enabled				= YES;
	mapItem.enabled				= YES;
}

-(IBAction)webClicked:(id)sender {
	showMap = YES;
	showWeb	= YES;
	
	[[[self.navigationController navigationBar] topItem] setTitle:@"VIEW: My Maps"];
	
	NSArray*			items	= [self toolbarItems];
	
	UIBarButtonItem*	tabItem	= [items objectAtIndex:1];
	UIBarButtonItem*	webItem	= [items objectAtIndex:3];
	UIBarButtonItem*	mapItem	= [items objectAtIndex:2];
	
	tabItem.enabled				= YES;
	webItem.enabled				= NO;
	mapItem.enabled				= YES;
}

-(IBAction)mapClicked:(id)sender {
	showMap = YES;
	showWeb	= NO;
	
	[[[self.navigationController navigationBar] topItem] setTitle:@"TRACE: My Maps"];
	
	NSArray*			items	= [self toolbarItems];
	
	UIBarButtonItem*	tabItem	= [items objectAtIndex:1];
	UIBarButtonItem*	webItem	= [items objectAtIndex:3];
	UIBarButtonItem*	mapItem	= [items objectAtIndex:2];
	
	tabItem.enabled				= YES;
	webItem.enabled				= YES;
	mapItem.enabled				= NO;		
}

-(IBAction)addClicked:(id)sender {
	// check if already added
	if (mapAdded) {
		return;
	}
	
	mapAdded = YES;	
	
	// add new map	
	GDataEntryMap *newEntry = [GDataEntryMap mapEntryWithTitle:@"New Map"];
	NSString *summaryStr	= [NSString stringWithFormat:@"Map created %@", [NSDate date]];
    
	[newEntry setSummaryWithString:summaryStr];
	[gmaps setActiveView:self];
	[gmaps addMap:newEntry];
}

-(IBAction)loginClicked:(id)sender {
	
	LoginViewController*		loginController = [[LoginViewController alloc] initWithNibName:@"Login" bundle:nil];
	
	if (loginController) {
		
		[loginController setActiveView:self];
		
		[loginController setGmaps:gmaps];
				
		[self presentModalViewController:loginController animated:YES];
				
		[loginController release];
	}
}


- (void)dealloc {
	
    [super dealloc];
}


@end

